<?php
// require '/usr/share/pear/SoapClient.php';
class PackageController extends FrontController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view'),
				'users'=>array('*'),
			),
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('getpackage','updatepackage','receivermo','book','index'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 
	public function actionCreate()
	{
		$model=new Package;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Package']))
		{
			$model->attributes=$_POST['Package'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Package']))
		{
			$model->attributes=$_POST['Package'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	*/
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
// 		$dataProvider=new CActiveDataProvider('Package');
		$user=Member::model()->findByPk(Yii::app ()->user->id);
		$packages=Package::model()->findAllByAttributes(array('type'=>2,'active'=>1));
		$this->render('index',array(
				'packages'=>$packages,
				'user'=>$user
				)
		);
	}
	
	public function actionBook($id)
	{
		try {
			$member=Member::model()->findByPk(Yii::app ()->user->id);
			$pack=$this->loadModel($id);
			$trans = Transpackage::model ()->findByAttributes ( array ('mid' => Yii::app ()->user->id,),array('order'=>'t.id DESC') );
			if ($trans != null) {
				if( strtotime($trans->enddate) >=  strtotime(date('Y-m-d H:i'))){
					Yii::app ()->user->setFlash ( 'warning', 'Tài khoản của bạn chưa hết thời gian sử dụng dịch vụ. Bạn chỉ có thể mua tiếp các gói dịch vụ khi đã hết thời gian sử dụng hiện tại.' );
					$this->redirect (array('member/about'));
				}
			}
			if($member->amount>=$pack->price){
				$date =date('Y-m-d H:i');
				$end_date = strtotime ( '+'.$pack->days.' day' , strtotime ( $date ) ) ;
				$end_date = date ( 'Y-m-d H:i' , $end_date );
				$trans=new Transpackage;
				$trans->mid=$member->id;
				$trans->pid=$pack->id;
				$trans->startdate=$date;
				$trans->enddate=$end_date;
				$trans->price=$pack->price;
				$trans->active=1;
				$trans->save();
				$member->amount=$member->amount-$pack->price;
				$member->save();
				$Session=new Session('User');
				$url=$Session->Get('url');
				$sdate = date_create($date);
				$sdate =  date_format($sdate,'H:i d-m-Y');
				
				$edate = date_create($end_date);
				$edate =  date_format($edate,'H:i d-m-Y');
				Yii::app ()->user->setFlash ( 'warning', 'Bạn đã mua gói '.$pack->name.'. Thời gian sử dụng của bạn từ '.$sdate.' đến '.$edate.'.' );
				if(isset($url)){
					$this->redirect ($url);
				}
				else{
					$this->redirect ( array ('/site/index') );
				}
			}
			else{
				Yii::app ()->user->setFlash ( 'warning', 'Tài khoản của bạn không đủ để mua gói cước '.$pack->name.'. Để tiếp tục sử dụng dịch vụ bạn vui lòng nạp thêm xu vào tài khoản.' );
				$this->redirect (array('member/about'));
			}
		}
		catch (Exception $ex){
			Yii::app ()->user->setFlash ( 'warning', $ex->getMessage());
			$this->redirect ( array ('/site') );
		}
	}
	
	public function actionGetPackage()
	{
		try{
			$Session=new Session('Script');
			$appid=Yii::app()->request->getParam('appId',0);
			$id=Yii::app()->request->getParam('productId',0);
			$sessionid=Yii::app()->request->getParam('sessionId','');
			$msisdn='0'.substr(Yii::app()->request->getParam('msisdn',''), 2);
			$md5=Yii::app()->request->getParam('md5','');
			
			PackageController::errorLogFile2('GET:----------------------');
			PackageController::errorLogFile2(CJSON::encode(
				array(
					'appId'=>$appid,
					'productId'=>$id,
					'sessionId'=>$sessionid,
					'msisdn'=>$msisdn,
					'md5'=>$md5
					)
				)
			);
			
			$type='package';
			$arr=array();
			$arr=explode('_', $id);
			if($arr[0]=='film'){
				$type='film';
				$id=$arr[1];
			}
			if($arr[0]=='clip'){
				$type='clip';
				$id=$arr[1];
			}
			
			$temp=new Temp;
			$temp->key=$sessionid;
			$temp->val=$msisdn;
			$temp->save();
			
			if($type=='film'){
				PackageController::errorLogFile2('GETFILM:----------------------');
				
				$film=Film::model()->findByPk($id);
				$package=Package::model()->findByPk($film->price);
				$parr=array(
						array(
								'id'=>$package->id,
								'name'=>$package->name,
								'price'=>$package->price,
								'url'=>Yii::app()->params['domain'].$this->createUrl('film/view',array('id'=>$film->id,'key'=>$temp->key)),
								'charge'=>true,
						)
				);
				PackageController::errorLogFile2(CJSON::encode($parr));
				if($id!=$Session->Get('id')){
					header('Content-type: application/json');
					$json=array(
							'id'=>$id,
							'name'=>$film->title,
							'description'=>$film->description,
							'previewUrl'=>Yii::app()->params['domain'].Yii::app()->request->baseUrl.$film->mobile_title,
							'cancelUrl'=>Yii::app()->params['domain'].$this->createUrl('/site/index'),
							'msisdn'=>$msisdn,
							'package'=>$parr,
					);
					echo CJSON::encode($json);
					PackageController::errorLogFile2(CJSON::encode($json));
					Yii::app()->end();
				}
				else{
					echo 'Error';
					PackageController::errorLogFile2('GETFILM:Session khong hop le. Server:'.$Session->Get('id').' - Mobilink:'.$id);
					Yii::app()->end();
				}
				
			}
			elseif ($type=='clip'){
				PackageController::errorLogFile2('GETCLIP:----------------------');
				
				$clip=Clip::model()->findByPk($id);
				$package=Package::model()->findByPk($clip->price);
				$parr=array(
						array(
								'id'=>$package->id,
								'name'=>$package->name,
								'price'=>$package->price,
								'url'=>Yii::app()->params['domain'].$this->createUrl('clip/view',array('id'=>$clip->id,'key'=>$temp->key)),
								'charge'=>true,
						)
				);
				PackageController::errorLogFile2(CJSON::encode($parr));
				if($id!=$Session->Get('id')){
					header('Content-type: application/json');
					$json=array(
							'id'=>$id,
							'name'=>$clip->name,
							'description'=>$clip->description,
							'previewUrl'=>Yii::app()->params['domain'].$clip->image,
							'cancelUrl'=>Yii::app()->params['domain'].$this->createUrl('/site/index'),
							'msisdn'=>$msisdn,
							'package'=>$parr,
					);
					echo CJSON::encode($json);
					PackageController::errorLogFile2(CJSON::encode($json));
					Yii::app()->end();
				}
				else{
					echo 'Error';
					PackageController::errorLogFile2('GETCLIP:Session khong hop le. Server:'.$Session->Get('id').' - Mobilink:'.$id);
					Yii::app()->end();
				}
				
			}
			else{
				
				$criteria=new CDbCriteria();
				$criteria->condition = 't.type =2 AND t.active=1 AND t.isdelete=0';
				$criteria->order='t.order ASC';
				$dataProvider=new CActiveDataProvider('Package', array(
						'criteria'=>$criteria,
				));
				$parray=array();
				foreach($dataProvider->getData() as $play =>$val){
					$arr=array(
						array(
							'id'=>$val['id'],
							'name'=>$val['name'],
							'price'=>$val['price'],
							'url'=>Yii::app()->params['domain'].$this->createUrl('member/about',array('key'=>$temp->key)),
							'charge'=>true,
						)
					);
					$parray=array_merge($parray,$arr);
				}
				if($id!=$Session->Get('id')){
					header('Content-type: application/json');
					$json=array(
							'id'=>$id,
							'name'=>'Đăng ký/Nạp tiền tài khoản MobileTV',
							'description'=>'Nạp tiền vào tài khoản MobileTV thông qua MobiLink.',
							'previewUrl'=>Yii::app()->params['domain'].Yii::app()->request->baseUrl.'/images/logo.jpg',
							'cancelUrl'=>Yii::app()->params['domain'].$this->createUrl('/site/index'),
							'msisdn'=>$msisdn,
							'package'=>$parray,
					);
					echo CJSON::encode($json);
					PackageController::errorLogFile2(CJSON::encode($json));
					Yii::app()->end();
				}
				else{
					echo 'Error';
					PackageController::errorLogFile2('GET:Session khong hop le. Server:'.$Session->Get('id').' - Mobilink:'.$id);
					Yii::app()->end();
				}
			}
		}
		catch (Exception $ex){
			PackageController::errorLogFile2('Exception:'.$ex->getMessage());
		}
	}
	public function actionUpdatePackage()
	{
		try{
			$Session=new Session('Script');
			$appid=Yii::app()->request->getParam('appId',0);
			$id=Yii::app()->request->getParam('productId',0);
			$sessionid=Yii::app()->request->getParam('sessionId','');
			$msisdn='0'.substr(Yii::app()->request->getParam('msisdn',''), 2);
			$md5=Yii::app()->request->getParam('md5','');
			$responsecode=Yii::app()->request->getParam('responsecode','');
			$responsereason=Yii::app()->request->getParam('responsereason','');
			$status=Yii::app()->request->getParam('status',false);
			$vsessionId=Yii::app()->request->getParam('vsessionId','');
			$amount=Yii::app()->request->getParam('amount',0);
			$action=Yii::app()->request->getParam('action',0);
			PackageController::errorLogFile2('UPDATE:----------------------');
			PackageController::errorLogFile2(CJSON::encode(
				array(
				'appId'=>$appid,
				'productId'=>$id,
				'sessionId'=>$sessionid,
				'msisdn'=>$msisdn,
				'md5'=>$md5,
				'responsecode'=>$responsecode,
				'responsereason'=>$responsereason,
				'status'=>$status,
				'vsessionId'=>$vsessionId,
				'amount'=>$amount,
				'action'=>$action,
				)
			));
			if($status){
				$member=Member::model()->findByAttributes(array('username'=>$msisdn));
				$pack=Package::model()->findByPk($action);
				if($member!=null){
					$member->amount=$member->amount+$pack->virtual_price;
					$trans=new Transpackage;
					$trans->mid=$member->id;
					$trans->pid=$pack->id;
					$trans->startdate=date('Y-m-d H:i');
					$trans->enddate=date('Y-m-d H:i');
					$trans->price=$pack->price;
					$trans->active=1;
					$trans->save();
					PackageController::errorLogFile2('Member:'.CJSON::encode($member));
					PackageController::errorLogFile2('Transaction:'.CJSON::encode($trans));
					if($member->save()){
						PackageController::errorLogFile2($msisdn.':Nap tien thanh cong. So tien nap:'.$amount.' dong');
						header('Content-type: application/json');
						echo CJSON::encode($member);
						Yii::app()->end();
					}
					else{
	// 					throw new CHttpException('Có lỗi khi cập nhật dữ liệu. Vui lòng thử lại sau.');
						PackageController::errorLogFile2($msisdn.':Co loi khi cap nhat du lieu.');
					}
				}
				else{
					$member=new Member;
					$member->username=$msisdn;
					$member->password=substr($sessionid,0,6);
					$member->activedate=date('Y-m-d H:i');
					$member->active=1;
					$member->vip=0;
					$member->amount=$pack->virtual_price;
					if($member->save()){
						$trans=new Transpackage;
						$trans->mid=$member->id;
						$trans->pid=$pack->id;
						$trans->startdate=date('Y-m-d H:i');
						$trans->enddate=date('Y-m-d H:i');
						$trans->price=$pack->price;
						$trans->active=1;
						$trans->save();
						PackageController::errorLogFile2($msisdn.':Dang ky thanh cong. So tien nap:'.$pack->price.' dong');
						header('Content-type: application/json');
						echo CJSON::encode($member);
						Yii::app()->end();
					}
					else{
	// 					throw new CHttpException('Không thể đăng ký tài khoản. Vui lòng thử lại sau.');
						PackageController::errorLogFile2($msisdn.':Co loi khi cap nhat du lieu');
					}
				}
			}
			else{
	// 			throw new CHttpException('Nạp tiền không thành công. Vui lòng thử lại sau.');
	// 			Yii::app()->user->setFlash('error', "Không thể đăng ký tài khoản. Vui lòng thử lại sau.");
				PackageController::errorLogFile2($msisdn.'-Mobilink: Nap tien khong thanh cong Mobilink');
			}
		}
		catch (Exception $ex){
			PackageController::errorLogFile2('Exception:'.$ex->getMessage());
		}
		
	}
	
	public function actionReceiverMO()
	{
		if($_SERVER['REMOTE_ADDR']=='203.113.137.163'){
// 		if(true){
			$res=0;
			$userid=Yii::app()->request->getParam('UserId','');
			$sevicesid=Yii::app()->request->getParam('ServiceId','');
			$commantcode=Yii::app()->request->getParam('CommandCode','');
			$message=Yii::app()->request->getParam('Message','');
			$mobioperator=Yii::app()->request->getParam('MobileOperator','');//Viết tắt các mạng di động: GPC, VMS, VTL, VNM
			$requestid=Yii::app()->request->getParam('RequestId','');
			$arr=array(
					'UserId'=>$userid,
					'ServiceId'=>$sevicesid,
					'CommandCode'=>$commantcode,
					'Message'=>$message,
					'MobileOperator'=>$mobioperator,
					'RequestId'=>$requestid,
			);
			PackageController::errorLogFile('--------------------------------------------');
			PackageController::errorLogFile(CJSON::encode($arr));
			//Validation
			if($userid==''){
				header('text/html; charset=utf-8');
				echo 1;
				PackageController::errorLogFile('MO:1');
				Yii::app()->end();
			}
			elseif($userid==''){
				header('text/html; charset=utf-8');
				echo 2;
				PackageController::errorLogFile('MO:2');
				Yii::app()->end();
			}
			elseif($commantcode==''){
				header('text/html; charset=utf-8');
				echo 3;
				PackageController::errorLogFile('MO:3');
				Yii::app()->end();
			}
			elseif($mobioperator==''){
				header('text/html; charset=utf-8');
				echo 5;
				PackageController::errorLogFile('MO:5');
				Yii::app()->end();
			}
			elseif($requestid==''){
				header('text/html; charset=utf-8');
				echo 6;
				PackageController::errorLogFile('MO:6');
				Yii::app()->end();
			}
			else{
				$message=urldecode($message);
				PackageController::errorLogFile('MO_MESSAGE:'.strtoupper($message));
				if(strtoupper($message)!='MTV'){
					if(strtoupper($message)=='MKTV'){
						$userid2='0'.substr($userid, 2);
						$member=Member::model()->findByAttributes(array('username'=>$userid2));
						if($member!=null){
							PackageController::errorLogFile('Get Password: '.$member->username);
							$info=base64_encode('Thue bao '.$member->username.', mat khau: '.$member->password.'. Cam on ban da su dung dich vu cua MOBILETV.');
							$params=array(
									'userId'=>$userid,
									'serviceId'=>$sevicesid,
									'commandCode'=>$commantcode,
									'info'=>$info,
									'messageType'=>1,
									'contentType'=>0,
									'requestId'=>$requestid
							);
							PackageController::sentMT($info,$params);
							header('text/html; charset=utf-8');
							echo 0;
							Yii::app()->end();
						}else{
							PackageController::errorLogFile('Get Password: '.$userid2);
							$info=base64_encode('Ban chua dang ky cho dich vu MOBILETV. De dang ky soan MTV gui 6776 (5000d/sms). Cam on ban da su dung dich vu cua MOBILETV.');
							$params=array(
									'userId'=>$userid,
									'serviceId'=>$sevicesid,
									'commandCode'=>$commantcode,
									'info'=>$info,
									'messageType'=>1,
									'contentType'=>0,
									'requestId'=>$requestid
							);
							PackageController::sentMT($info,$params);
							header('text/html; charset=utf-8');
							echo 0;
							Yii::app()->end();
						}
					}
					else{
						$des=str_replace(' ', '', strtoupper($message));
						$des=str_replace('MTV', '', $des);
						$member_des=Member::model()->findByAttributes(array('username'=>$des));
						if($member_des!=null){
							$type=$sevicesid=='6776'?'3':'4';
							$pack=Package::model()->findByAttributes(array('type'=>$type,'active'=>'1'));
							$return=PackageController::updateAccount($member_des, $pack);
							if($return==0){
									PackageController::errorLogFile('MO:'.$return);
									PackageController::errorLogFile($userid.' - SEND: '.$member_des->username);
									$info=base64_encode('Quy khach vua chuyen cho thue bao '.$member_des->username.' so tien '.$pack->price.' dong cho dich vu MOBILETV.');
									$params=array(
											'userId'=>$userid,
											'serviceId'=>$sevicesid,
											'commandCode'=>$commantcode,
											'info'=>$info,
											'messageType'=>1,
											'contentType'=>0,
											'requestId'=>$requestid
									);
									PackageController::sentMT($info,$params);
									header('text/html; charset=utf-8');
									echo 0;
									Yii::app()->end();
							}
							else{
								$info=base64_encode('Thanh toan loi. Vui long thu lai sau. Cam on ban da su dung dich vu cua MOBILETV.');
								$params=array(
										'userId'=>$userid,
										'serviceId'=>$sevicesid,
										'commandCode'=>$commantcode,
										'info'=>$info,
										'messageType'=>1,
										'contentType'=>0,
										'requestId'=>$requestid
								);
								PackageController::sentMT($info,$params);
								header('text/html; charset=utf-8');
								echo -1;
								PackageController::errorLogFile('MT:'.$return);
								Yii::app()->end();
							}
						}
					}
				}
				$userid2='0'.substr($userid, 2);
				$member=Member::model()->findByAttributes(array('username'=>$userid2));
				$type=$sevicesid=='6776'?'3':'4';
				$pack=Package::model()->findByAttributes(array('type'=>$type,'active'=>'1'));
				if($member!=null){
					$return=PackageController::updateAccount($member, $pack);
					PackageController::errorLogFile($member->username.':Update Amount');
					if($return==0){
						header('text/html; charset=utf-8');
						echo 0;
						PackageController::errorLogFile('MO:'.$return);
						$info=base64_encode('Quy khach vua thanh toan '.$pack->price.' dong cho dich vu MOBILETV. Cam on ban da su dung dich vu cua MOBILETV.');
						$params=array(
									'userId'=>$userid,
									'serviceId'=>$sevicesid,
									'commandCode'=>$commantcode,
									'info'=>$info,
									'messageType'=>1,
									'contentType'=>0,
									'requestId'=>$requestid
						);
						PackageController::sentMT($info,$params);
						Yii::app()->end();
					}
					else{
						
						$info=base64_encode('Thanh toan loi. Vui long thu lai sau. Cam on ban da su dung dich vu cua MOBILETV.');
						$params=array(
								'userId'=>$userid,
								'serviceId'=>$sevicesid,
								'commandCode'=>$commantcode,
								'info'=>$info,
								'messageType'=>1,
								'contentType'=>0,
								'requestId'=>$requestid
						);
						PackageController::sentMT($info,$params);
						header('text/html; charset=utf-8');
						echo -1;
						PackageController::errorLogFile('MT:'.$return);
						Yii::app()->end();
					}
					Yii::app()->end();
				}
				else{
					$member=new Member;
					$member->username=$userid2;
					$member->password=substr(time(),0,6);
					$member->activedate=date('Y-m-d H:i');
					$member->active=1;
					$member->vip=0;
					$member->amount=$pack->virtual_price;
					if($member->save()){
						PackageController::errorLogFile($member->username.':Create Account');

						$date =date('Y-m-d H:i');
						$end_date = strtotime ( '+'.$pack->days.' day' , strtotime ( $date ) ) ;
						$end_date = date ( 'Y-m-d H:i' , $end_date );
						$trans=new Transpackage;
						$trans->mid=$member->id;
						$trans->pid=$pack->id;
						$trans->startdate=$date;
						$trans->enddate=$end_date;
						$trans->price=$pack->price;
						$trans->active=1;
						$trans->save();
						header('text/html; charset=utf-8');
						echo 0;
						PackageController::errorLogFile('MO:0');
						$info=base64_encode('Quy khach vua thanh toan '.$pack->price.' dong cho dich vu MOBILETV. Tai khoan dang nhap:'.$member->username.'. Mat khau: '.$member->password.' . Cam on ban da su dung dich vu cua MOBILETV.');
						$params=array(
								'userId'=>$userid,
								'serviceId'=>$sevicesid,
								'commandCode'=>$commantcode,
								'info'=>$info,
								'messageType'=>1,
								'contentType'=>0,
								'requestId'=>$requestid
						);
						PackageController::sentMT($info,$params);
						Yii::app()->end();
					}
					else{
						$info=base64_encode('Thanh toan loi. Vui long thu lai sau. Cam on ban da su dung dich vu cua MOBILETV.');
						$params=array(
								'userId'=>$userid,
								'serviceId'=>$sevicesid,
								'commandCode'=>$commantcode,
								'info'=>$info,
								'messageType'=>1,
								'contentType'=>0,
								'requestId'=>$requestid
						);
						PackageController::sentMT($info,$params);
						header('text/html; charset=utf-8');
						echo $return;
						PackageController::errorLogFile('M0:-1');
						Yii::app()->end();
					}
				}
			}
		}
		else{
			PackageController::errorLogFile('--------------------------------------------');
			header('text/html; charset=utf-8');
			echo 'Access denied';
			PackageController::errorLogFile('M0: Access denied');
			Yii::app()->end();
		}
	}
	public function updateAccount($member,$pack){
		$member->amount=$pack->virtual_price+$member->amount;
		$trans=new Transpackage;
		$trans->mid=$member->id;
		$trans->pid=$pack->id;
		$trans->startdate=date('Y-m-d H:i');
		$trans->enddate=date('Y-m-d H:i');
		$trans->price=$pack->price;
		$trans->active=1;
		$trans->save();
		if($member->save()){
			return 0;
		}
		else{
			// throw new CHttpException('Có lỗi khi cập nhật dữ liệu. Vui lòng thử lại sau.');base64_encode($data->file_data)
			return -1;
		}
	}
	public function creatAccount($userid,$pack){
		$member=new Member;
		$member->username=$userid;
		$member->password=substr(time(),0,6);
		$member->activedate=date('Y-m-d H:i');
		$member->active=1;
		$member->vip=0;
		$member->amount=$pack->virtual_price;
		if($member->save()){
			$trans=new Transpackage;
			$trans->mid=$member->id;
			$trans->pid=$pack->id;
			$trans->startdate=date('Y-m-d H:i');
			$trans->enddate=date('Y-m-d H:i');
			$trans->price=$pack->price;
			$trans->active=1;
			$trans->save();
			return $member;
		}
		else{
			// 	throw new CHttpException('Không thể đăng ký tài khoản. Vui lòng thử lại sau.');
			return null;
		}
	}
	
	public function sentMT($info,$params=array()){
		try{
			PackageController::errorLogFile('MESSAGE: '.base64_decode($info));
			$client = new SoapClient("http://203.113.137.163/mt-services/MTService?WSDL", array(
					'login'          => "zigmasms",
					'password'       => "zigsms1369"));
			$client->soap_defencoding = 'UTF-8';
			PackageController::errorLogFile(CJSON::encode($params));
			$return = $client->__call('sendMT',$params); //sendMT
			PackageController::errorLogFile('MT:'.$return);
			return $return;
		}
		catch (Exception $ex){
			PackageController::errorLogFile('Exception:'.$ex->getMessage());
			return -1;
		}
	}
	
	public function errorLogFile($msg){
		$log = new Logging();
		$pathlog=Yii::app()->params['pathLogFile'];
		// set path and name of log file (optional)
		$log->lfile($pathlog);
			
		// write message to the log file
		$log->lwrite($msg);
	
		$log->lclose();
	}
	public function errorLogFile2($msg){
		$log = new Logging();
		$pathlog=Yii::app()->params['pathLogFile_MBL'];
		// set path and name of log file (optional)
		$log->lfile($pathlog);
			
		// write message to the log file
		$log->lwrite($msg);
	
		$log->lclose();
	}
// 	public function sendMT($params){
		
// 	}
	/**
	 * Manages all models.
	 
	public function actionAdmin()
	{
		$model=new Package('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Package']))
			$model->attributes=$_GET['Package'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Package::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='package-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
